<?php
require_once "database.php";
header('content-type: application/json');
$return_array = array('error_code' => 0, 'error_msg' => '','data' => '');
if(isset($_POST['info'])){
    // process post request
    $info = json_decode($_POST['info']);
    
    $user_id = property_exists($info, 'user_id') ? $info->user_id : false;
    $title = property_exists($info, 'title') ? $info->title: false;
    $introduction = property_exists($info, 'introduction') ? $info->introduction : false;
    if($user_id != false && $title != false && $introduction!=false){
        $sql = sprintf("insert into content (user_id, title, introduction) 
            values ('%s', '%s', '%s')", $user_id, $title, $introduction);
        $result = mysqli_query($link, $sql);
        if($result == false){
            $return_array['error_code']=-4;
            $return_array['error_msg'] = '数据库错误';            
        }
    }
    else{
        $return_array['error_code']=-3;
        $return_array['error_msg'] = '未设置必有参数';
    }
}
else{
    // process get request
    if(isset($_GET['offset']) && isset($_GET['num'])){
        $offset = intval($_GET['offset']);
        $num = intval($_GET['num']);
        $sql = sprintf("select title, introduction from content limit
            %d, %d", $offset, $num);
        $result = mysqli_query($link, $sql);
        if($result == false){
            $return_array['error_code']=-2;
            $return_array['error_msg'] = '数据库错误';            
        } 
        else{
            $return_array['data'] = $result->fetch_all();
        }
    }
    else{
        $return_array['error_code']=-1;
        $return_array['error_msg'] = '未设置必有参数';        
    }
}
echo json_encode($return_array);
?>
